﻿using Csla.Core;
using Csla.Rules;
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Csla.Rules.CommonRules;
using NetFrameworkExtensions.BusinessLayer.Csla4.Properties;

namespace NetFrameworkExtensions.BusinessLayer.Csla4.Rules
{
  public class IsCultureNameRule : CommonBusinessRule
  {
    public IsCultureNameRule(IPropertyInfo primaryProperty)
      : base(primaryProperty)
    {
      if (!primaryProperty.Type.IsAssignableFrom(typeof(string)))
        throw new ArgumentException("Property must accept string values");
      
      MinCultureType = CultureTypes.InstalledWin32Cultures;
      MaxCultureType = CultureTypes.AllCultures | CultureTypes.FrameworkCultures;
    }

    public CultureTypes? MinCultureType { get; set; }
    public CultureTypes? MaxCultureType { get; set; }

    protected override void Execute(RuleContext context)
    {
      string value = this.ReadProperty(context.Target, PrimaryProperty) as string;
      if (value != null)
      {
        try
        {
          var culture = CultureInfo.GetCultureInfo(value);
          if (MinCultureType.HasValue && (MinCultureType.Value & culture.CultureTypes) != MinCultureType.Value)
          {
            context.AddErrorResult(FormattedResources.ExIsCultureNameRuleMinCultureError(value, MinCultureType.Value.ToString(), culture.CultureTypes.ToString()));
            return;
          }
          if (MaxCultureType.HasValue && (MaxCultureType.Value | culture.CultureTypes) != MaxCultureType.Value)
          {
            context.AddErrorResult(string.Format(Resources.ExIsCultureNameRuleMaxCultureError, value, MaxCultureType.Value, culture.CultureTypes));
            return;
          }
        }
        catch (Exception ex)
        {
          context.AddErrorResult(ex.Message);
        }
      }
    }
  }
}
